package com.zkingsoft.actions.admin;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.BusinessConstance;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.DataDictionary;
import com.zkingsoft.model.Userinfo;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ExcelImport;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.plugin.util.FileDownload;
import com.zkingsoft.plugin.util.FileUtils;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.serviceUtil.ServiceUtil;
import com.zkingsoft.services.DataDictionaryService;
import com.zkingsoft.services.UserinfoService;

/**
 * 员工管理类
 * @date 2016-11-17 11:32
 */
@Controller
@RequestMapping(value = "admin/userinfo")
public class UserinfoController extends BaseController{

	@Resource
	private UserinfoService userinfoService;
	@Resource
	private DataDictionaryService dataDictionaryService;//数据字典
	@Resource
	private ServiceUtil serviceUtil;
	
	private String thisIsTestGit;
	/**
	 * @Description:  查询所有的员工
	 * @author:dingchuan
	 * @return   
	 * 返回类型 AjaxResult
	 * @date 2016年12月17日
	 */
	 
	@RequestMapping(value = "/showAllStaff")
	public @ResponseBody AjaxResult showAllStaff() {
 		List<Userinfo> staffList = userinfoService.findByModel(null);
 		if(staffList!=null && staffList.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"成功",staffList,staffList.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR,null,"失败");
	}
	
	
	
	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Userinfo userinfo, PaginationVO pageVo) {
		return showList(userinfoService, userinfo, pageVo);
	}
   	
	/**
	 * 新增或者修改页面
	 */   
	@RemoveRequestToken	
   	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(Userinfo userinfo) {
		
		if (userinfo.getuId() != null) {
			return modify(userinfoService, userinfo, "员工");
		} else {
			//判断员工姓名是否存在
			if (serviceUtil.addCheckRepeat("userinfo", "u_name", userinfo.getuName())){
			      throw new GlobleException("该员工已经存在");
			}
			return add(userinfoService, userinfo, "员工");
		}
	}
	
   	/**
	 * 进入修改界面
	 */   
	@SaveRequestToken
   	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		Userinfo userinfo;
		if (id != null) {
			userinfo = userinfoService.findById(id);
			WebUtil.getRequest().setAttribute("obj", userinfo);
		}
		return "admin/staff-form";
	}
   	
   	
   	/**
	 * 删除
	 */  
 	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(userinfoService, keys);
	}
 	
 	
 	
 	
 	
 	
 	
 	/**
 	 * @Description:查询所有的部门
 	 * @author:dingchuan
 	 * @return
 	 * 返回类型 AjaxResult
 	 * @date 2016年12月12日
 	 */
 	@RequestMapping(value = "/queryAllDepart")
	public @ResponseBody AjaxResult queryAllDepart() {		
 		DataDictionary lookDepart = new DataDictionary();
 		lookDepart.setType(BusinessConstance.DATA_TYPE_DEPART);
 		List<DataDictionary> departs = dataDictionaryService.findByModel(lookDepart);
 		if(departs!=null && departs.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", departs, departs.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}
 	
 	/**
 	 * @Description:查询所有的职位
 	 * @author:dingchuan
 	 * @return
 	 * 返回类型 AjaxResult
 	 * @date 2016年12月12日
 	 */
 	@RequestMapping(value = "/queryAllPostion")
	public @ResponseBody AjaxResult queryAllPostion() {		
 		DataDictionary lookDepart = new DataDictionary();
 		lookDepart.setType(BusinessConstance.DATA_TYPE_POSTION);
 		List<DataDictionary> postions = dataDictionaryService.findByModel(lookDepart);
 		if(postions!=null && postions.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK, null, "查询成功", postions, postions.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR, null, "查询失败");
	}
 	
 	/*============================导入导出相关操作============================*/
 	
 	
 	
 	/**
 	 * 导出员工信息
 	* @Title: export 
 	* @param @param model
 	* @param @param request
 	* @param @param response
 	* @param @param userinfo
 	* @param @return    设定文件 
 	* @return ModelAndView    返回类型 
 	* @throws
 	 */
	@RequestMapping(value = "/export")  
    public @ResponseBody ModelAndView export(ModelMap model, HttpServletRequest request, HttpServletResponse response,Userinfo userinfo) {  
		HSSFWorkbook workbook = ExcelUtil.generateExcel("员工信息表",new String[]{"工号","姓名","性别","所属部门","职位","电话","入职时间"},userinfoService.export(userinfo) );    
          try {
        	  ViewExcel.buildExcel(null, workbook, request, response,"员工信息表.xls");    
          } catch (Exception e) {    
              e.printStackTrace();    
          }
          return new ModelAndView(new ViewExcel(), model);
    } 
	
	
	/**
 	 * @Description:下载模板
 	 * @author:dingchuan
 	 * @param response
 	 * @throws Exception
 	 * 返回类型 void
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value="/downExcelModel")
   	public void downExcelModel(HttpServletResponse response) throws Exception{
   		String path = WebUtil.getResourceRealPath("WEB-INF/views/admin/staff_import_model.xlsx");   		
   		FileDownload.fileDownload(response, path, "员工导入模板.xlsx");
   	}
 	
	private static final Logger log = Logger.getLogger(UserinfoController.class);
 	
 	/**
 	 * @Description:导入excel
 	 * @author:dingchuan
 	 * @param response
 	 * @param request
 	 * @param file
 	 * @return
 	 * 返回类型 AjaxResult
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value = "/importData")
	public @ResponseBody AjaxResult importData(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		// 记录成功的导入多少条数据
		int count = 0;
		// 构造对象的集合
		List<Userinfo> staffList = new ArrayList<Userinfo>();
		response.setContentType("text/html;charset=UTF-8");
		String fileName = file.getOriginalFilename();
		String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
		if (!extension.equals("xls") && !extension.equals("xlsx")) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "请选择excel文件！！！");
		}
		String dirPath = request.getSession().getServletContext().getRealPath("/") + "fileupload";
		File fileDir = new File(dirPath);
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		try {
			if (!fileDir.exists()) {
				if (fileDir.mkdirs()) {
				}
			}
			File saveFile = new File(dirPath + "/" + fileName);
			file.transferTo(saveFile);
			List<List<Object>> list = ExcelImport.readExcel(saveFile, fileName, null, 5);
			// 由于读取excel的工具类会从标题行开始读取，因此，list=null或者size=1表示只有标题行说明没有数据可以导入
			if (list == null || list.size() <= 1) {
				throw new GlobleException("没有数据可导入");
			}
			for (int i = 1; i < list.size(); i++) {
				Userinfo staff = new Userinfo();//每一行
				List<Object> objList = list.get(i);
				int t = i+1;
				if(objList.get(0)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的员工姓名没有填写");
   	   			}else{
   	   				String staffName = ((String)objList.get(0)).trim();//员工姓名
   	   				staff.setuName(staffName);
   	   			}
				
				if(objList.get(1)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的员工性别没有填写");
   	   			}else{
   	   				String uSex = ((String)objList.get(1)).trim();//员工性别
   	   				staff.setuSex(uSex);
   	   			}
				
				if(objList.get(2)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的所属部门没有填写");
   	   			}else{
   	   				String uDepartment = ((String)objList.get(2)).trim();//所属部门
   	   				staff.setuDepartment(uDepartment);
   	   			}
				
				if(objList.get(3)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的担任职位没有填写");
   	   			}else{
   	   				String uJob = ((String)objList.get(3)).trim();//担任职位
   	   				staff.setuJob(uJob);
   	   			}
				
				if(objList.get(4)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的手机号没有填写");
   	   			}else{
   	   				String phone = ((String)objList.get(4)).trim();//手机号
   	   				//判断手机的格式
	   	 			if(!Pattern.matches(BusinessConstance.REGX_PHONE, phone)){
	   	 				return new AjaxResult(AjaxResult.STATUS_ERR, "", "导入失败!因为第"+t+"行的手机号格式错误");
	   	 			}
	   	 			staff.setuPhone(phone);
   	   			}
				
				if(objList.get(5)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的入职时间没有填写");
   	   			}else{
   	   				String uJobdate = ((String)objList.get(5)).trim();//入职时间\
   	   				Date date;
   	   				try {
   	   					date = sdf.parse(uJobdate);
					} catch (Exception e) {
						log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的入职时间填写格式不正确");
					}
   	   				staff.setuJobdate(date);
   	   			}
				//判断员工姓名是否存在
				if (serviceUtil.addCheckRepeat("userinfo", "u_name", staff.getuName())){
				      throw new GlobleException("导入失败!因为第"+t+"行的员工已经存在");
				}
				staffList.add(staff);
			}
			count =	userinfoService.adds(staffList);
		} catch (IOException e) {
			log.error("导入异常");
		}finally {
			FileUtils.deleteDir(fileDir);
		}
		if (count > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "成功导入" + count + "条数据!");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!");
		}
	}
	
}